﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using TomNet.Data;
using TomNet.Entity;

namespace TomNet.AspNetCore.Mvc.Filters
{
    /// <summary>
    /// 全局异常捕获过滤器
    /// </summary>
    public class GlobalExceptionFilter : IAsyncExceptionFilter
    {
        private readonly ILogger _logger;
        private readonly ILoggerFactory _loggerFactory;

        public GlobalExceptionFilter(ILoggerFactory loggerFactory)
        {
            _loggerFactory = loggerFactory;
            _logger = _loggerFactory.CreateLogger(GetType());
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {
            Exception ex = context.Exception;

            // 自定义异常处理
            //if (context.Exception.GetType() == typeof(XXXException))
            //{
            //    // to do
            //}

            // 如果异常没有被处理则进行处理
            if (context.ExceptionHandled == false)
            {
                //　输出日志
                _logger.LogError(ex, ex.Message);

                var result = new OpResult<string>();
                result.NotOK(status: ApiResultCode.SystemInnerError, msg: ex.Message);
                // 标准的Http状态码处理方式
                // context.Result = ApiResult.ToApiResult(result);
                // 这是传统的处理方式，并不将异常信息以HTTP状态码返回给客户端
                context.Result = new OkObjectResult(result);
            }
            context.ExceptionHandled = true;
            return Task.CompletedTask;
        }
    }
}
